package com.stars.home.activity

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.core.net.toUri
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.baidu.mapapi.search.core.PoiInfo
import com.eazypermissions.common.model.PermissionResult
import com.eazypermissions.coroutinespermission.PermissionManager
import com.google.gson.Gson
import com.luck.picture.lib.PictureSelector
import com.qmuiteam.qmui.kotlin.onClick
import com.stars.home.adapter.DyInfoAdapter
import com.stars.home.adapter.DynamicAdapter
import com.stars.home.base.MBActivity
import com.stars.home.config.MIntentAction
import com.stars.home.databinding.ActivityPersonalInfoBinding
import com.stars.home.inte.ChoiceData
import com.stars.home.inte.OnUploadCallback
import com.stars.home.model.GoodsImgBean
import com.stars.home.model.bean.UpImgBean
import com.stars.home.utils.ChosePhotoUtils
import com.stars.home.utils.FileUtils
import com.stars.home.utils.OssUtils
import com.stars.home.utils.PopuListUtils
import com.stars.home.vmodel.PersonalInfoVModel
import com.trailer.base.utils.UiSwitch
import com.trailer.base.utils.UiUtils
import kotlinx.coroutines.launch
import java.io.File
import java.util.ArrayList
import kotlin.reflect.typeOf

/**
 *on 2021/5/16
 */
class PersonalInfoActivity : MBActivity<PersonalInfoVModel, ActivityPersonalInfoBinding>(),
    OnUploadCallback<UpImgBean> {


    private var recordAdapter: DyInfoAdapter? = null

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        vm.getUserInfo()


        initAdapter()

        vm.user.observe(this) {

            if (null!=it.sex&&it.sex.equals("1")) {
                vm.sex = "1"
                binding.tvSex.text = "男"

            } else {
                vm.sex = "0"
                binding.tvSex.text = "女"
            }
            //设置图片
            if(null!=it.lifePhoto&&it.lifePhoto!=""){
                var s=it.lifePhoto.split(",")
                for(item in s){
                    val bugAttachment = GoodsImgBean(0, item, 0, false)
                    recordAdapter!!.addData(recordAdapter!!.data.size - 1, bugAttachment)
                    vm.nopath.add(item)
                }
            }

            //工作经验
            vm.workTime = it.workTime
            if(null!=it.workTime) {
                binding.tvWork.text = it.workTime + "年"
            }else{
                binding.tvWork.text =  "0年"

            }
            vm.address = it.address
            binding.tvAddress.text = it.address


        }




        vm.typeChose.observe(this) {
            if (it == 1) {//头像
                //选择照片

                lifecycleScope.launch {
                    if (PermissionManager.requestPermissions(
                            this@PersonalInfoActivity, 1000,
                            Manifest.permission.CAMERA,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                        ) is PermissionResult.PermissionGranted
                    ) {
                        ChosePhotoUtils.getChosePhoto(view()!!.context(), 1)

                    }

                }


            } else {//图片
                //选择照片

                lifecycleScope.launch {
                    if (PermissionManager.requestPermissions(
                            this@PersonalInfoActivity, 1000,
                            Manifest.permission.CAMERA,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                        ) is PermissionResult.PermissionGranted
                    ) {
                        ChosePhotoUtils.getChosePhoto(view()!!.context(), 9)

                    }

                }
            }
        }


    }

    fun initAdapter() {

        val attachement: java.util.ArrayList<GoodsImgBean> = java.util.ArrayList<GoodsImgBean>()

        val bean = GoodsImgBean(-1, "", -1, false)
        attachement.add(bean)

        val left = UiUtils.dp2Px(context(), 3f)
        val itemDecoration: RecyclerView.ItemDecoration = object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(
                outRect: Rect,
                view: View,
                parent: RecyclerView,
                state: RecyclerView.State
            ) {
                super.getItemOffsets(outRect, view, parent, state)
                val childAdapterPosition = parent.getChildAdapterPosition(view)
                val i = childAdapterPosition % 3
                if (i != 0) {
                    outRect.left = left
                }
                outRect.top = left
            }
        }
        recordAdapter = DyInfoAdapter(vm, attachement)

        binding.recyclerView.addItemDecoration(itemDecoration)
        binding.recyclerView.adapter = recordAdapter

    }

    override fun listeners() {
        super.listeners()


        binding.llChoseAddress.onClick {

            lifecycleScope.launch {
                if (PermissionManager.requestPermissions(
                        this@PersonalInfoActivity, 1000,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    ) is PermissionResult.PermissionGranted
                ) {
                    UiSwitch.singleRes(
                        this@PersonalInfoActivity,
                        ChoseBaiDuActivity::class.java, MIntentAction.REQUEST_CODE_ONE
                    )
                }

            }


        }

        binding.llWork.onClick {
            var list = ArrayList<String>()
            for (index in 1..40){
                list.add(index.toString())
            }
            PopuListUtils.showQMUIPopup(context(), binding.llWork, list, object : ChoiceData {
                override fun onRestuse(context: String?) {
                    vm.workTime = context
                    binding.tvWork.text = context + "年"
                }

            })
        }


        binding.llSex.onClick {
            var list = ArrayList<String>()
            list.add("男")
            list.add("女")
            PopuListUtils.showQMUIPopup(context(), binding.tvSex, list, object : ChoiceData {
                override fun onRestuse(context: String?) {
                    if (context.equals("男")) {
                        vm.sex = "1"
                    } else {
                        vm.sex = "0"
                    }

                    binding.tvSex.text = context
                }

            })
        }
        binding.llSubmit.onClick {

            if (vm.name.isNullOrEmpty()) {

                toast("请输入昵称")
                return@onClick
            }
            if (vm.sex.isNullOrEmpty()) {

                toast("请选择性别")
                return@onClick
            }
            if (vm.workTime.isNullOrEmpty()) {

                toast("请选择工作年限")
                return@onClick
            }
            if (vm.address.isNullOrEmpty()) {

                toast("请选择地址")
                return@onClick
            }
            //todo
            var images = ""
            if (vm.nopath.size != 0) {

                for (item in vm.nopath) {
                    if (TextUtils.isEmpty(images)) {
                        images = item
                    } else {
                        images = "$images,$item"
                    }
                }
            }
            vm.toSubmit(images)

        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) {
            return
        }
        if (requestCode == MIntentAction.REQUEST_CODE_ONE) {
            val bundle = data!!.extras
            if (null != bundle) {
                var data = bundle.getString("bean")
                val item: PoiInfo = Gson().fromJson(data, PoiInfo::class.java)
                vm.address = item.address
                binding.tvAddress.text = item.address

            }


            return
        }

        if (requestCode == MIntentAction.REQUEST_CODE_IMG) {//图片

            val selectList = PictureSelector.obtainMultipleResult(data)
            val list = ArrayList<String>()
            if (null != selectList) {
                for (item in selectList) {

                    if (item.path.contains("content://")) {

                        val cr = this.contentResolver
                        list.add(FileUtils.getFilePathFromContentUri(item.path.toUri(), cr))
                    } else {
                        list.add(item.path)
                    }

//                    //添加一个默认
//                    val bugAttachment = GoodsImgBean(0, "", 0, true)
//                    recordAdapter!!.addData(recordAdapter!!.data.size - 1, bugAttachment)
//                    vm.nopath.add("")
                }


                OssUtils(this, vm)
                    .setUpLoad("avatar", list, this)

            }


            return

        }
        if (requestCode == MIntentAction.REQUEST_CODE_CAMERA) {//拍照
            //拍照
            val selectList = PictureSelector.obtainMultipleResult(data) ?: return
            val list = ArrayList<String>()
            if (selectList[0].path.contains("content://")) {

                val cr = this.contentResolver
                list.add(FileUtils.getFilePathFromContentUri(selectList[0].path.toUri(), cr))

            } else {
                list.add(selectList[0].path)
            }

            binding.imgAvater.load(File(list[0]))

            // vm.headImg.value=list[0]
            OssUtils(this, vm)
                .setUpLoad("avatar", list, this)

            return
        }


    }


    override fun vmClass(): Class<PersonalInfoVModel> {
        return PersonalInfoVModel::class.java
    }

    override fun binding(): ActivityPersonalInfoBinding {
        return ActivityPersonalInfoBinding.inflate(layoutInflater)
    }

    override fun title(): String? {
        return "个人信息"
    }

    override fun onUploadSuccess(t: UpImgBean) {

        if (vm.typeChose.value == 1) {
            vm.headImg.value = t.url
        } else {
            if (null != t.url) {
                val bugAttachment = GoodsImgBean(0, t.url!!, 0, false)
                recordAdapter!!.addData(recordAdapter!!.data.size - 1, bugAttachment)
                vm.nopath.add(t.url!!)
            }
        }


    }

    override fun onUploadError(error: String?) {

    }
}
